<?php
/**
 * Created by 沧月
 * User: Lhhhh丶
 * Date: 2019/5/4
 * Time: 22:52
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\User as UserModel;
use app\api\model\UserAddress;
use app\api\service\Token as TokenService;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;

class Address extends BaseController
{
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'getUserAddress,createorupdateaddress']
    ];

    /**
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws UserException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserAddress(){
        $uid = TokenService::getCurrentUid();
        $userAddress = UserAddress::where('user_id',$uid)
            ->find();
        if(!$userAddress){
            throw new UserException([
                'msg' => '用户地址不存在',
                'errorCode' => 60001
            ]);
        }
        return $userAddress;
    }

    /**
     * @return \think\response\Json
     * @throws UserException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\exception\DbException
     */
    public function createorupdateaddress(){
        $validat = new AddressNew();
        $validat->goCheck();
        //根据Token来获取uid
        //根据uid来查找用户数据，并判断用户是否存在，如果不存在抛出异常
        //获取用户从客户端提交来的地址信息
        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        if(!$user){
            throw new UserException();
        }
        $dataArray = $validat->getDataByRule(input('post.'));
        $userAddrsee = $user->address;
        if(!$userAddrsee){
            $user->address()->save($dataArray); //创建
        }else{
            $user->address->save($dataArray);   //更新
        }
//        return $user;
        return json(new SuccessMessage(),'201');
    }
}